package database;

import java.util.ArrayList;

import struct.CommentInfo;
import struct.SellerInfo;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class Helper {

	public static SellerInfo GetSellerInfo(String seller)
	{
		SellerInfo sellerInfo = new SellerInfo();
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		
		Query qRatings = new Query("Rating").addFilter("SELLER", FilterOperator.EQUAL,seller);
		Iterable<Entity> ratings = ds.prepare(qRatings).asIterable();
		int count =0;
		double sum =0;
		double average;
		for(Entity rating : ratings )
		{
			count++;
			sum+= Double.parseDouble((String) rating.getProperty("RATE"));
		}
		average = (sum/count)*10;
		
		sellerInfo.username = seller;
		sellerInfo.rating = (int) Math.round(average);
		sellerInfo.ratingCount = count;
		
		return sellerInfo;
	}
	
	public static ArrayList<CommentInfo> GetCommentInfo(String seller)
	{
		ArrayList<CommentInfo> list = new ArrayList<CommentInfo>();
		
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		
		Query qComments = new Query("Comment").addFilter("SELLER", FilterOperator.EQUAL,seller).addSort("TIME", Query.SortDirection.DESCENDING);
		Iterable<Entity> comments = ds.prepare(qComments).asIterable();
		int count =0;
		double sum =0;
		double average;
		for(Entity comment : comments )
		{
			CommentInfo c = new CommentInfo();
			
			c.seller = seller;
			c.commenter = (String) comment.getProperty("COMMENTOR");
			c.comment = (String) comment.getProperty("COMMENT");
			c.time = (String) comment.getProperty("TIME");
			
			list.add(c);
		}
		
		return list;
	
	}
}
